package jp.wug.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class NamedObjects<T> {
    private final Map<T, String> namedObjects = new HashMap<T, String>();
    private final Map<String, T> map = new HashMap<String, T>();

    public String giveName(T t, String candidate) {
        if (namedObjects.containsKey(t)) {
            return namedObjects.get(t);
        }
        String name = renameIfExists(candidate, t);
        namedObjects.put(t, name);
        return name;
    }

    public String getName(T t) {
        assert namedObjects.containsKey(t);
        return namedObjects.get(t);
    }

    public T get(String name) {
        return map.get(name);
    }

    public Set<String> keySet() {
        return map.keySet();
    }

    private String renameIfExists(String candidate, T value) {
        if (!map.containsKey(candidate)) {
            map.put(candidate, value);
            return candidate;
        }
        int n = 2;
        String s = candidate + "_" + n;
        while (map.containsKey(s)) {
            s = candidate + "_" + (n++);
        }
        map.put(s, value);
        return s;
    }
}
